﻿using System;
using System.Collections.Generic;
using System.Linq;
using ARchGL.Declaration.Platform.Domain.Entities;
using TDF.Core.Configuration;
using TDF.Core.Exceptions;
using TDF.Core.Ioc;
using TDF.Core.Operator;
using TDF.Data.Repository;

namespace ARchGL.Declaration.Platform.Service
{
    public class AdminService : IAdminService
    {
        public OperatorModel Login(string userName, string password)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase<Admin>>())
            {
                var admin = repository.FindEntity(x => x.Account == userName);
                if (admin.IsNullOrDeleted())
                {
                    throw new KnownException("账户不存在，请重新输入");
                }
                if (password != admin.Password)
                {
                    throw new KnownException("密码不正确，请重新输入");
                }
                var oper = BuildOperator(admin);
                Ioc.Resolve<IOperatorProvider>().AddCurrent(oper);
                return oper;
            }
        }

        public void LoginOut()
        {
            Ioc.Resolve<IOperatorProvider>().RemoveCurrent();
        }

        private OperatorModel BuildOperator(Admin admin)
        {
            return new OperatorModel()
            {
                Id = admin.Id,
                ExpiredTime = DateTime.Now.AddMinutes(Configs.Instance.SessionExpireMinute),
                IsSystem = true,
                LoginTime = DateTime.Now,
                UserName = admin.Account,
                RoleIds = new List<Guid>()
            };
        }
    }
}
